<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品页面</title>
    <!-- 引入样式 -->
    <!--    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">-->
    <!--    <link rel="stylesheet" type="text/css" href="./static/css/elementuifont.css"/>-->
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="../../static/js/Vue-2.6.12.js" type="text/javascript" charset="utf-8"></script>
    <script src="../../static/js/axios.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"></script>

    <style>
        .el-row {
            margin-bottom: 20px;

        &
        :last-child {
            margin-bottom: 0;
        }

        }
        .el-col {
            border-radius: 4px;
        }

        .grid-content {
            border-radius: 4px;
            min-height: 36px;
        }

        .row-bg {
            padding: 10px 0;
            background-color: #f9fafc;
        }

        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-drawer {
            overflow: scroll;
        }
    </style>
</head>
<body>
<div id="app">

    <el-row>
        <el-col :span="3">
            <div class="grid-content"></div>
        </el-col>
    </el-row>
    <el-row>
        <el-col :span="3">
            <div class="grid-content"></div>
        </el-col>
        <el-col :span="18">
            <el-form :inline="true" :model="searForm" class="demo-form-inline">
                <el-form-item>
                    <el-input clearable v-model="searForm.id" placeholder="id"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input clearable v-model="searForm.name" placeholder="商品名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="findList">查询</el-button>
                    <el-button type="success" @click="dialogFormVisible = true,template = {}">新增</el-button>
                </el-form-item>
            </el-form>

            <el-table
                    :data="dataList"
                    border
                    style="width: 100%">
                <el-table-column
                        prop="id"
                        label="id"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="name"
                        label="商品名"
                        width="180">
                </el-table-column>
                <el-table-column
                        label="商品预览图"
                        width="180">
                    <template slot-scope="scope">
                        <el-image
                                style="width: 100px; height: 100px"
                                :src="scope.row.image"
                                fit="scale-down"></el-image>
                    </template>
                </el-table-column>
                <el-table-column
                        label="状态"
                        width="180">
                    <template slot-scope="scope">
                        <el-switch
                                style="display: block"
                                v-model="scope.row.status"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                active-text="通过"
                                inactive-text="未通过"
                                active-value="1"
                                inactive-value="0"
                                @change="changeStatus">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作">
                    <template slot-scope="scope">
                        <el-link type="primary" @click="getbyid(scope.row.id)">编辑</el-link>
                        <el-link type="danger" @click="del(scope.row.id)">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="findList"
                    @current-change="findList"
                    :current-page.sync="currentPage"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size.sync="pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-col>
        <el-col :span="3">
            <div class="grid-content bg-purple"></div>
        </el-col>
    </el-row>


    <el-drawer
            title="商品编辑!"
            :before-close="handleClose"
            :visible.sync="dialog"
            direction="rtl"
            custom-class="demo-drawer"
            ref="drawer"
            size="60%" @opened="showEditor" @closed="closeEditor">
        <div class="demo-drawer__content">
            <el-form :model="goods">
                <el-form-item label="商品名称" label-width="80px">
                    <el-input v-model="goods.spu.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="副标题" label-width="80px">
                    <el-input v-model="goods.spu.caption" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="品牌" label-width="80px">
                    <el-select v-model="goods.spu.brandId" placeholder="请选择">
                        <el-option
                                v-for="brand in brandList"
                                :key="brand.id"
                                :label="brand.name"
                                :value="brand.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分类" label-width="80px">
                    <el-cascader
                            v-model="categoryids"
                            :options="categoryList"></el-cascader>
                </el-form-item>
                <el-form-item label="商品主图" label-width="80px">
                    <el-upload
                            class="avatar-uploader"
                            action="/file/uploadimg.do?dir=spu"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="图片列表" label-width="80px">
                    <el-upload
                            action="/file/uploadimg.do?dir=spu/spuimages"
                            list-type="picture-card"
                            :file-list="imgList"
                            :limit="5"
                            :on-preview="handlePictureCardPreview"
                            :on-success="updateSpuImages"
                            :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>
                <el-form-item label="商品介绍">
                </el-form-item>
                <div id="editor"></div>
                <el-form-item label="更新规格" label-width="80px">
                    <el-radio v-model="radio" label="1">更新</el-radio>
                    <el-radio v-model="radio" @change="showSkuListDialog" label="2">编辑</el-radio>
                </el-form-item>
                <el-form-item label="规格模板" label-width="80px" v-show="radio==1?true:false">
                    <el-select v-model="goods.spu.templateId" placeholder="请选择">
                        <el-option
                                v-for="template in templateList"
                                :key="template.id"
                                :label="template.name"
                                :value="template.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="规格选择" label-width="80px" v-show="radio==1?true:false">
                    <div v-for="(spec,index) in specItems" :key="index">
                        {{spec.name}}
                        <el-checkbox-group v-model="specs">
                            <el-checkbox @change="addSpecnewSpecItems($event,spec.name,op)" v-for="op in spec.options"
                                         :label="op"></el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
                {{newSpecItems}}
            </el-form>
            <div class="demo-drawer__footer">
                <el-button @click="updateSpuSkuList" type="success">更新</el-button>
            </div>
        </div>
    </el-drawer>

    <!--sku列表的dialog-->
    <el-dialog title="sku列表" :visible.sync="dialogSkuListVisible" width="80%">
        <el-form ref="form" :model="goods" label-width="80px">
            <el-table
                    :data="goods.skuList"
                    border
                    style="width: 100%">
                <el-table-column
                        prop="name"
                        label="名称"
                        width="180">
                </el-table-column>

                <el-table-column
                        label="价格(分)"
                        width="180">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.price"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                        label="数量"
                        width="180">
                    <template slot-scope="scope">
                        <el-input-number size="mini" v-model="scope.row.num"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column
                        label="预警数量"
                        width="180">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.alertNum" size="mini"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column
                        label="是否上架"
                        width="180">
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.status"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                active-value="1"
                                inactive-value="0">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="success">删除</el-button>
                        <el-button type="success" @click="getSkuId(scope.row.id)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
        <el-button type="success" @click="saveSkuList">批量保存</el-button>
    </el-dialog>

    <el-dialog title="保存" :visible.sync="skuVisible">
        <el-form label-position="right" label-width="80px" :model="sku">
            <el-form-item label="名称">
                <el-input v-model="sku.name"></el-input>
            </el-form-item>
            <el-form-item label="活动区域">
                <el-input v-model="sku.image"></el-input>
            </el-form-item>
            <el-form-item label="活动形式">
                <el-input v-model="sku.images"></el-input>
            </el-form-item>
        </el-form>
        <el-button type="success" @click="saveSku">保存</el-button>
    </el-dialog>

</div>
</body>

<script type="text/javascript">
    new Vue({
        el: "#app",
        data: {
            dataList: [],
            currentPage: 1,
            pagesize: 20,
            total: 100,
            searForm: {},
            dialogFormVisible: false,
            formLabelWidth: "180px",
            goods: {spu: {}, skuList: [], specList: []},
            dialog: false,
            brandList: [],
            categoryids: [],
            categoryList: [],
            imageUrl: '',
            dialogImageUrl: "",
            dialogVisible: false,
            imgList: [],
            templateList: [],
            specItems: [],
            specs: [],
            radio: 0,
            newSpecItems: null,
            dialogSkuListVisible: false,
            skuList: [],
            sku: {},
            skuVisible: false,
            editor:null
        },
        created() {
            this.findList()
        },
        methods: {
            findList() {
                axios.post(`/spu/findconditionpage.do?startpage=${this.currentPage}&pagesize=${this.pagesize}`, this.searForm).then((res) => {
                    this.dataList = res.data.records
                    this.total = res.data.total
                })
            },
            save() {
                let id = this.template.id
                let action = id ? 'update' : 'save';
                axios.post(`/template/${action}.do`, this.template).then((res) => {
                    if (res.data.code == "200") {
                        this.dialogFormVisible = false
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        });
                        this.findList()
                    } else {
                        this.$message.error(res.data.msg)
                    }
                })
            },
            del(id) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.get(`/spu/delbyid.do?id=${id}`).then((res) => {
                        if (res.data.code == "200") {
                            this.dialogFormVisible = false
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.findList()
                        } else {
                            this.$message.error(res.data.msg + " " + res.data.ex)
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            getbyid(id) {
                axios.get(`/spu/findsgoodsbyid.do?spuid=${id}`).then((res) => {
                    this.$message({
                        type: 'success',
                        message: '查询成功!'
                    });
                    this.goods = res.data

                    this.imageUrl = this.goods.spu.image
                    /*
                     this.categoryids.push(this.goods.spu.category1Id)
                     this.categoryids.push(this.goods.spu.category2Id)
                     this.categoryids.push(this.goods.spu.category3Id)
                     */
                    this.categoryids = [this.goods.spu.category1Id, this.goods.spu.category2Id, this.goods.spu.category3Id]
                    this.imgList = []
                    this.imgList = JSON.parse(this.goods.spu.images)
                })

                axios.get(`/brand/findall.do`).then((res) => {
                    this.brandList = res.data
                })

                axios.get(`/category/findcategorymenu.do`).then((res) => {
                    this.categoryList = res.data
                })

                axios.get(`/template/findall.do`).then((res) => {
                    this.templateList = res.data
                })

                // this.findByTemplateId()


                this.dialog = true
            },
            findByTemplateId(templateId) {
                // console.log(this.goods.spu.templateId)
                // let templateId = this.goods.spu.templateId;
                axios.get(`/spec/findbytemplateid.do?templateId=${templateId}`).then((res) => {
                    this.specItems = res.data
                    this.specItems.forEach((spec) => {
                        spec.options = spec.options.split(",")
                    })
                })
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {
                    });
            },
            handleAvatarSuccess(res, file) {
                console.log(res, file)
                this.imageUrl = URL.createObjectURL(file.raw);
                this.goods.spu.image = res
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            updateSpuImages(response, file, fileList) {
                fileList.forEach((f)=>{
                    f.url = f.response
                })
                this.goods.spu.images = fileList
            },
            addSpecnewSpecItems($event, key, value) {
                // console.log($event)
                // newSpecItems
                // console.log(key,value)
                // 第一次执行该方法
                if (this.newSpecItems == null) {
                    this.newSpecItems = {[key]: [value]}
                    console.log(this.newSpecItems)
                } else {
                    if ($event) {
                        // 单独提一个方法用来寻找key是否存在
                        let isFlag = this.searchKey(this.newSpecItems, key)
                        if (isFlag) { // 如果当前key已存在在newSpecItems里面就push
                            this.newSpecItems[key].push(value)
                        } else {
                            // 不在就新构建一个key-value
                            this.newSpecItems[key] = []
                            this.newSpecItems[key].push(value)
                        }
                    } else {
                        this.newSpecItems[key].splice(this.newSpecItems[key].indexOf(value), 1)
                    }
                }
            },
            searchKey(newSpecItems, key) {
                for (spec in newSpecItems) {
                    if (spec == key) {
                        return true
                    }
                }
                return false;
            },
            showSkuListDialog() {
                axios.get(`/sku/findbyspuid.do?spuId=${this.goods.spu.id}`).then((res) => {
                    this.skuList = res.data
                    this.goods.skuList = this.skuList
                    this.dialogSkuListVisible = true
                })
            },
            updateSpuSkuList() {

                this.goods.spu.category1Id = this.categoryids[0]
                this.goods.spu.category2Id = this.categoryids[1]
                this.goods.spu.category3Id = this.categoryids[2]

                this.goods.spu.newSpecItems = this.newSpecItems


                let data = this.newSpecItems
                let keys = []
                for (k in data) {
                    // console.log(k)
                    keys.push(k)
                }

                // 最终的数据，{}是为了能够进入数组
                var specList = [{}]
                for (var i = 0; i < keys.length; i++) {
                    var newdata = []
                    // 遍历我们keys，确定最终需要组合数据的次数
                    for (var j = 0; j < data[keys[i]].length; j++) {
                        // 确定当前最终数据中的长度，循环次数
                        for (var n = 0; n < specList.length; n++) {

                            newdata.push({...specList[n], [keys[i]]: data[keys[i]][j]})
                        }
                    }
                    specList = newdata
                }

                console.log(specList)
                this.goods.specList = specList

                this.goods.spu.introduction = this.editor.txt.html()
                axios.post(`/spu/updateSpuSkuList.do`, this.goods).then((res) => {
                    if (res.data.code == 200) {
                        this.$message.success(res.data.msg)
                    }
                })
            },
            saveSkuList() {
                axios.post(`/sku/updateSkuList.do`, this.goods).then((res) => {
                    if (res.data.code == 200) {
                        this.$message.success(res.data.msg)
                        this.showSkuListDialog()
                    }
                })
            },
            getSkuId(id) {
                axios.get(`/sku/findbyid.do?skuId=${id}`).then((res) => {
                    this.sku = res.data
                    this.skuVisible = true
                })
            },
            saveSku() {
                axios.post(`/sku/updatesku.do`, this.sku).then((res) => {
                    this.skuVisible = false
                    this.showSkuListDialog()
                })
            },
            showEditor(){
                const  E = window.wangEditor
                // 创建编辑器
                this.editor = new E(`#editor`)
                this.editor.create()

                this.editor.txt.html(this.goods.spu.introduction)
            },
            closeEditor(){
                // 销毁编辑器
                this.editor.destroy()
                this.editor = null
            },
            changeStatus(status){
                console.log(status)
            }
        },
        watch: {
            'goods.spu.templateId': {
                handler(newV) {
                    console.log(newV)
                    this.findByTemplateId(newV)
                }
            }
        }
    })
</script>
</html>